package co.yixiang.common.config;

import co.yixiang.common.interceptor.PermissionInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 拦截器配置类，用于注册自定义拦截器和配置资源处理
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    // 文件路径配置
    @Value("${file.path}")
    private String path;

    // 用户头像路径配置
    @Value("${file.avatar}")
    private String avatar;

    /**
     * 创建并返回一个权限拦截器实例
     * @return 权限拦截器实例
     */
    @Bean
    public HandlerInterceptor getPermissionInterceptor() {
        return new PermissionInterceptor();
    }

    /**
     * 注册权限拦截器到拦截器注册表中
     * @param registry 拦截器注册表
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.getPermissionInterceptor());
    }

//    /**
//     * 创建并返回跨域过滤器实例，用于处理跨域请求
//     * @return 跨域过滤器实例
//     */
//    @Bean
//    public CorsFilter corsFilter()  {
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        CorsConfiguration config = new CorsConfiguration();
//        config.setAllowCredentials(true);
//        config.addAllowedOrigin("*");
//        config.addAllowedHeader("*");
//        config.addAllowedMethod("*");
//        source.registerCorsConfiguration("/**", config);
//        return new CorsFilter(source);
//
//    }

    /**
     * 配置资源处理器，用于处理静态资源请求
     * @param registry 资源处理器注册表
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String avatarUtl = "file:" + avatar.replace("\\","/");
        String pathUtl = "file:" + path.replace("\\","/");
        // 用户头像资源处理器
        registry.addResourceHandler("/avatar/**").addResourceLocations(avatarUtl).setCachePeriod(0);
        // 文件资源处理器
        registry.addResourceHandler("/file/**").addResourceLocations(pathUtl).setCachePeriod(0);
        // 其他静态资源处理器
        registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0);
    }
}
